using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using ProgramLauncher.Models;
using ProgramLauncher.Utils;
using System.Text;

namespace ProgramLauncher
{
    public partial class MainForm : Form
    {
        private AppConfig config;
        private Panel mainPanel;
        private FlowLayoutPanel buttonPanel;
        private Button configButton;
        private StatusStrip statusStrip;
        private ToolStripStatusLabel statusLabel;

        public MainForm()
        {
            // 先加载配置，避免 OnResize 事件中的空引用
            LoadConfig();

            // 主面板
            mainPanel = new Panel
            {
                Dock = DockStyle.Fill
            };
            Controls.Add(mainPanel);

            // 按钮面板
            buttonPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                AutoScroll = true,
                Padding = new Padding(20),
                FlowDirection = FlowDirection.LeftToRight,
                WrapContents = true
            };
            mainPanel.Controls.Add(buttonPanel);

            // 配置按钮
            configButton = new Button
            {
                Text = "⚙",
                Font = new Font("Segoe UI", 16F),
                Size = new Size(50, 50),
                FlatStyle = FlatStyle.Flat,
                BackColor = Color.FromArgb(240, 240, 240),
                Cursor = Cursors.Hand
            };
            configButton.FlatAppearance.BorderSize = 0;
            configButton.Click += ConfigButton_Click;
            mainPanel.Controls.Add(configButton);

            // 状态栏
            statusStrip = new StatusStrip
            {
                BackColor = Color.FromArgb(240, 240, 240),
                SizingGrip = false,
                Height = 50,
                Padding = new Padding(10, 5, 10, 5)  // 添加内边距
            };

            statusLabel = new ToolStripStatusLabel
            {
                Font = new Font("Microsoft YaHei UI", 11F),
                AutoSize = false,
                Spring = true,
                TextAlign = ContentAlignment.MiddleLeft,
                AutoToolTip = true,
                Margin = new Padding(10, 0, 10, 0)  // 添加左右边距
            };

            statusStrip.Items.Add(statusLabel);
            Controls.Add(statusStrip);

            // 窗体设置
            Text = "程序启动器";
            MinimumSize = new Size(400, 300);
            StartPosition = FormStartPosition.CenterScreen;

            // 应用保存的窗体设置
            if (config?.WindowSettings != null)
            {
                if (config.WindowSettings.Width > 0 && config.WindowSettings.Height > 0)
                {
                    Size = new Size(
                        Math.Min(config.WindowSettings.Width, Screen.PrimaryScreen.WorkingArea.Width),
                        Math.Min(config.WindowSettings.Height, Screen.PrimaryScreen.WorkingArea.Height)
                    );
                }
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            
            // 应用保存的窗体设置
            if (config?.WindowSettings != null)
            {
                // 获取所有屏幕
                var screens = Screen.AllScreens;
                bool isValidPosition = false;

                // 检查保存的位置是否在任何一个屏幕范围内
                foreach (var screen in screens)
                {
                    Rectangle bounds = screen.WorkingArea;
                    Point savedLocation = new Point(config.WindowSettings.Left, config.WindowSettings.Top);
                    Size savedSize = new Size(config.WindowSettings.Width, config.WindowSettings.Height);

                    // 检查位置是否在屏幕工作区内
                    if (bounds.Contains(savedLocation) && 
                        bounds.Contains(new Point(savedLocation.X + savedSize.Width, savedLocation.Y + savedSize.Height)))
                    {
                        Location = savedLocation;
                        isValidPosition = true;
                        break;
                    }
                }

                // 如果位置无效，居中显示
                if (!isValidPosition)
                {
                    StartPosition = FormStartPosition.CenterScreen;
                }

                // 如果设置为最大化，在设置位置和大小后再最大化
                if (config.WindowSettings.IsMaximized)
                {
                    WindowState = FormWindowState.Maximized;
                }
            }

            RefreshButtons();
            UpdateConfigButtonPosition();
            LogManager.LogInfo("主窗体已加载");
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            
            // 只更新界面布局，不保存设置
            UpdateConfigButtonPosition();
            UpdateButtonLayout();

            // 如果状态栏有文本，重新计算其高度
            if (!string.IsNullOrEmpty(statusLabel?.Text))
            {
                ShowStatus(statusLabel.Text, statusLabel.ForeColor == Color.Red);
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            // 保存窗体设置
            if (config.WindowSettings == null)
            {
                config.WindowSettings = new WindowSettings();
            }

            if (WindowState == FormWindowState.Maximized)
            {
                config.WindowSettings.IsMaximized = true;
            }
            else if (WindowState == FormWindowState.Normal)
            {
                config.WindowSettings.IsMaximized = false;
                config.WindowSettings.Width = Width;
                config.WindowSettings.Height = Height;
                config.WindowSettings.Left = Left;
                config.WindowSettings.Top = Top;
            }

            try
            {
                ConfigManager.SaveConfig(config);
            }
            catch (Exception ex)
            {
                LogManager.LogError("保存窗体设置失败", ex);
            }
        }

        private void UpdateConfigButtonPosition()
        {
            // 将配置按钮放在右下角，留出状态栏的空间
            configButton.Location = new Point(
                mainPanel.Width - configButton.Width - 20,
                mainPanel.Height - configButton.Height - statusStrip.Height - 20
            );
            configButton.BringToFront();
        }

        private void UpdateButtonLayout()
        {
            // 计算可用空间
            int availableWidth = buttonPanel.ClientSize.Width - buttonPanel.Padding.Horizontal;
            
            // 计算最佳按钮大小
            int minButtonWidth = 150;
            int maxButtonWidth = 200;
            int buttonHeight = 80;
            int spacing = 20;

            // 计算每行可以放置的按钮数量
            int buttonsPerRow = Math.Max(1, availableWidth / (minButtonWidth + spacing));
            
            // 计算实际按钮宽度（在最小和最大宽度之间）
            int buttonWidth = Math.Min(maxButtonWidth, 
                Math.Max(minButtonWidth, (availableWidth - (buttonsPerRow - 1) * spacing) / buttonsPerRow));

            // 更新所有按钮的大小
            foreach (Control control in buttonPanel.Controls)
            {
                if (control is Button button && button != configButton)
                {
                    button.Size = new Size(buttonWidth, buttonHeight);
                    button.Margin = new Padding(spacing / 2);
                }
            }
        }

        private void RefreshButtons()
        {
            buttonPanel.Controls.Clear();

            if (config.Buttons != null)
            {
                foreach (var buttonConfig in config.Buttons)
                {
                    var button = new Button
                    {
                        Text = buttonConfig.Name,
                        Tag = buttonConfig,
                        Font = new Font("Microsoft YaHei UI", 12F),
                        FlatStyle = FlatStyle.Flat,
                        BackColor = Color.White,
                        Cursor = Cursors.Hand,
                        UseVisualStyleBackColor = true,
                        AutoEllipsis = true
                    };
                    button.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
                    button.Click += LaunchButton_Click;
                    buttonPanel.Controls.Add(button);
                }
            }

            UpdateButtonLayout();
        }

        private void ConfigButton_Click(object sender, EventArgs e)
        {
            using (var configForm = new ConfigForm(config))
            {
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        ConfigManager.SaveConfig(config);
                        RefreshButtons();
                        ShowStatus("配置已更新", false);
                    }
                    catch (Exception ex)
                    {
                        LogManager.LogError("保存配置失败", ex);
                        ShowStatus("保存配置失败", true);
                    }
                }
            }
        }

        private void LaunchButton_Click(object sender, EventArgs e)
        {
            if (sender is Button button && button.Tag is ButtonConfig buttonConfig)
            {
                try
                {
                    if (!File.Exists(buttonConfig.ProgramPath))
                    {
                        string errorMessage = $"程序文件不存在: {buttonConfig.ProgramPath}";
                        LogManager.LogError(errorMessage);
                        ShowStatus(errorMessage, true);
                        return;
                    }

                    // 获取完整路径
                    string fullPath = Path.GetFullPath(buttonConfig.ProgramPath);
                    
                    // 检查程序是否已经在运行
                    string processName = Path.GetFileNameWithoutExtension(buttonConfig.ProgramPath);
                    var runningProcesses = System.Diagnostics.Process.GetProcessesByName(processName);
                    
                    foreach (var proc in runningProcesses)
                    {
                        try
                        {
                            string procPath = proc.MainModule?.FileName;
                            if (!string.IsNullOrEmpty(procPath) && 
                                string.Equals(Path.GetFullPath(procPath), fullPath, StringComparison.OrdinalIgnoreCase))
                            {
                                string warningMessage = $"程序\"{buttonConfig.Name}\"（{procPath}）已在运行，\r\n请先退出后再启动";
                                LogManager.LogInfo(warningMessage);
                                ShowStatus(warningMessage, true);
                                
                                // 尝试激活已运行的窗口
                                if (!proc.HasExited && proc.MainWindowHandle != IntPtr.Zero)
                                {
                                    NativeMethods.SetForegroundWindow(proc.MainWindowHandle);
                                }
                                
                                proc.Dispose();
                                return;
                            }
                        }
                        catch (System.ComponentModel.Win32Exception)
                        {
                            // 无法访问进程路径时跳过（可能是权限问题）
                            continue;
                        }
                        finally
                        {
                            proc.Dispose();
                        }
                    }

                    var process = System.Diagnostics.Process.Start(buttonConfig.ProgramPath);
                    string successMessage = $"已启动程序: {buttonConfig.Name}";
                    LogManager.LogInfo(successMessage);
                    ShowStatus(successMessage, false);

                    // 监控程序退出
                    if (process != null)
                    {
                        process.EnableRaisingEvents = true;
                        process.Exited += (s, args) =>
                        {
                            // 由于 Exited 事件在不同线程中触发，需要使用 Invoke 来更新 UI
                            if (!IsDisposed && !Disposing)
                            {
                                Invoke(new Action(() =>
                                {
                                    string exitMessage = $"程序已退出: {buttonConfig.Name}";
                                    LogManager.LogInfo(exitMessage);
                                    ShowStatus(exitMessage, false);
                                }));
                            }
                        };
                    }
                }
                catch (Exception ex)
                {
                    string errorMessage = $"启动程序失败: {buttonConfig.Name}";
                    LogManager.LogError(errorMessage, ex);
                    ShowStatus(errorMessage, true);
                }
            }
        }

        // 添加 NativeMethods 类来处理窗口激活
        private static class NativeMethods
        {
            [System.Runtime.InteropServices.DllImport("user32.dll")]
            public static extern bool SetForegroundWindow(IntPtr hWnd);
        }

        private void ShowStatus(string message, bool isError)
        {
            if (statusStrip == null || statusLabel == null) return;

            statusLabel.ForeColor = isError ? Color.Red : Color.Black;
            
            // 计算状态栏可用宽度（减去左右边距）
            int availableWidth = statusStrip.ClientSize.Width - 40;
            
            // 使用 Graphics 对象测量文本并处理换行
            using (var g = CreateGraphics())
            {
                // 先按换行符分割文本
                var textLines = message.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
                var lines = new List<string>();

                foreach (var textLine in textLines)
                {
                    if (string.IsNullOrEmpty(textLine))
                    {
                        lines.Add(string.Empty);
                        continue;
                    }

                    // 将每一行按空格分割成单词
                    var words = textLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    var currentLine = new StringBuilder();
                    float currentLineWidth = 0;

                    foreach (var word in words)
                    {
                        // 测量当前单词的宽度
                        SizeF wordSize = g.MeasureString(word + " ", statusLabel.Font);

                        // 如果加上这个单词会超出可用宽度，就开始新的一行
                        if (currentLineWidth + wordSize.Width > availableWidth && currentLine.Length > 0)
                        {
                            lines.Add(currentLine.ToString().TrimEnd());
                            currentLine.Clear();
                            currentLineWidth = 0;
                        }

                        // 添加单词到当前行
                        currentLine.Append(word).Append(" ");
                        currentLineWidth += wordSize.Width;
                    }

                    // 添加最后一行
                    if (currentLine.Length > 0)
                    {
                        lines.Add(currentLine.ToString().TrimEnd());
                    }
                }

                // 计算所需的总高度
                float lineHeight = g.MeasureString("测试", statusLabel.Font).Height;
                int totalHeight = Math.Max(50, (int)(lines.Count * lineHeight + 16)); // 16为上下padding

                // 更新状态栏高度
                if (statusStrip.Height != totalHeight)
                {
                    statusStrip.Height = totalHeight;
                    UpdateConfigButtonPosition();
                }

                // 设置状态标签属性
                statusLabel.AutoSize = false;
                statusLabel.Size = new Size(availableWidth, totalHeight);

                // 使用换行符连接所有行
                statusLabel.Text = string.Join(Environment.NewLine, lines);
            }

            // 确保状态栏立即重绘
            statusStrip.Refresh();
        }

        private void LoadConfig()
        {
            try
            {
                config = ConfigManager.LoadConfig();
                if (config == null)
                {
                    config = new AppConfig { Buttons = new List<ButtonConfig>() };
                    ConfigManager.SaveConfig(config);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    $"加载配置文件时出错：{ex.Message}",
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                config = new AppConfig { Buttons = new List<ButtonConfig>() };
            }
        }
    }
} 